package com.gusha.service;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gusha.dao.SysOrderDao;
import com.gusha.model.ReceivingAddress;
import com.gusha.model.SysOrder;
import com.gusha.model.SysShopping;
import com.gusha.model.SysTraining;
import com.gusha.model.TrainComm;
import com.gusha.model.User;

@Service
@Transactional
public class SysOrderService {
	@Autowired
	private SysOrderDao sysOrderDao;
	
	
	public Page<SysOrder> findAll(Pageable pageable, SysOrder sysOrder) {
        @SuppressWarnings("serial")
        Page<SysOrder> result = sysOrderDao.findAll(new Specification<SysOrder>() {
            @Override
            public Predicate toPredicate(Root<SysOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (sysOrder.getId() != null) {
                    list.add(cb.equal(root.get("id").as(BigInteger.class),sysOrder.getId()));
                }
                if (sysOrder.getShoppingId() != null) {
                    list.add(cb.equal(root.get("shoppingId").as(SysShopping.class),sysOrder.getShoppingId()));
                }
                if (sysOrder.getAddressId() != null) {
                    list.add(cb.equal(root.get("addressId").as(ReceivingAddress.class),sysOrder.getAddressId()));
                }
                if (sysOrder.getCommodityNum() != null) {
                    list.add(cb.equal(root.get("commodityNum").as(BigInteger.class),sysOrder.getCommodityNum()));
                }
                if (sysOrder.getIsDelete() != null) {
                    list.add(cb.equal(root.get("isDelete").as(BigInteger.class),sysOrder.getIsDelete()));
                }
                if (sysOrder.getUserId() != null) {
                    list.add(cb.equal(root.get("userId").as(User.class),sysOrder.getUserId()));
                }
                if (sysOrder.getState() != null) {
                    list.add(cb.equal(root.get("state").as(BigInteger.class),sysOrder.getState()));
                }
                if (sysOrder.getAddTime() != null) {
                    list.add(cb.equal(root.get("addTime").as(Date.class),sysOrder.getAddTime()));
                }
                
                
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },pageable);
         return result;
    }
}
